package com.zon.len.mp.extend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zon.len.mp.extend.mapper.ExtendBaseMapper;
import com.zon.len.mp.extend.service.IServiceExtend;
import com.zon.len.mp.extend.utils.ObjectCopy;
import com.zon.len.mp.extend.wrapper.LambdaExtendWrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ZL since on 2021/12/18 下午9:23
 */
public abstract class ServiceExtendImpl<M extends ExtendBaseMapper<T>, T> extends
    ServiceImpl<M, T> implements
    IServiceExtend<T> {

  @Autowired
  protected M extendBaseMapper;

  @Override
  public M getBaseMapper() {
    return extendBaseMapper;
  }

  @Override
  public <EV, E> List<EV> joinList(LambdaExtendWrapper<E> wrapper, Class<EV> clz) {
    List<Map<String, Object>> objectMap = extendBaseMapper.joinSelectList(wrapper);
    if (CollectionUtils.isEmpty(objectMap)) {
      return new ArrayList<>();
    }
    return ObjectCopy.map(objectMap, clz);
  }

  @Override
  public <E, EV> EV joinGetOne(LambdaExtendWrapper<E> wrapper, Class<EV> clz) {
    Map<String, Object> objectMap = extendBaseMapper.joinSelectOne(wrapper);

    if (null == objectMap) {
      return null;
    }
    return ObjectCopy.map(objectMap, clz);
  }

  @Override
  public <E> long joinCount(LambdaExtendWrapper<E> wrapper) {
    return extendBaseMapper.joinSelectCount(wrapper);
  }

  @Override
  public <EV, E extends IPage<EV>, C> Page<EV> joinPage(E page, LambdaExtendWrapper<C> wrapper,
      Class<EV> clz) {
    IPage<Map<String, Object>> selectPage = extendBaseMapper
        .joinSelectPage(new Page<>(page.getCurrent(), page.getSize()), wrapper);
    // 获取列表
    List<Map<String, Object>> pageRecords = selectPage.getRecords();
    List<EV> parseArray = ObjectCopy.map(pageRecords, clz);
    selectPage.setRecords(null);
    Page<EV> returnPage = new Page<>();
    BeanUtils.copyProperties(selectPage, returnPage);
    return returnPage.setRecords(parseArray);
  }


}
